<!--
 * @Author: zhao 13370229059@163.com
 * @Date: 2024-09-16 19:54:57
 * @LastEditors: zhao 13370229059@163.com
 * @LastEditTime: 2025-01-14 11:13:08
 * @FilePath: \dance\pages\online\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="online">
    <!-- 头部 -->
    <uv-status-bar></uv-status-bar>
    <!--自定义头部 -->
    <z-navbar title=""></z-navbar>
    <view class="online-video">
      <view class="online-video-main">
        <m-video
          loop
          autoplay
          controls
          show-speed-rate-btn
          show-mute-btn
          show-casting-button
          enable-auto-rotation
          show-background-playback-button
          enable-play-gesture
          :src="activeVideo"
          token="AsMqnVHVX5siSwwz4ckDCOCHCim5XsvNNXR1GkIVmrs="
          @play="onPlay"
          object-fit="cover"
          ref="mVideoRef"
          @ended="tally('play')"
        />
      </view>
      <view class="online-video-info">
        <template v-if="activeSuccess != -1 && ajaxData.lessonItems?.length">
          {{ ajaxData.lessonItems[activeSuccess]?.lessonName }}
        </template>
      </view>
    </view>
    <view class="scroll">
      <view class="online-label">
        <view class="share">
          <button open-type="share" class="reset-button">分享</button>
        </view>
        <view class="collect" @click="httpCollect" :style="{ color: ajaxData.collected?.id ? '#FF7A66' : '#000' }">
          {{ ajaxData.collected?.id === 0 ? '+收藏' : '已收藏' }}
        </view>
      </view>
      <view class="online-info">
        {{ ajaxData.lessonName }}
      </view>
      <view class="online-teacher">
        <view class="teacher">
          <uv-avatar size="96rpx" :src="ajaxData.teacherPhoto || defaultImages[2]" mode="aspectFill" />
          <view class="content">
            <view class="name">{{ ajaxData.teacherName }}</view>
            <xzj-readMore hideLineNum="3" v-if="ajaxData.teacherDesc" style="line-height: 41.86rpx">
              {{ ajaxData.teacherDesc }}
            </xzj-readMore>
          </view>
        </view>
        <uv-line color="#959595"></uv-line>
        <view class="introduce">
          <view class="title">课程介绍</view>
          <view class="rate">
            课程难度：
            <view class="grade">{{ gradeOptions.find(r => r.val === ajaxData.grade)?.label }} </view>
          </view>
          <xzj-readMore hideLineNum="3" v-if="ajaxData.description" style="line-height: 41.86rpx">
            {{ ajaxData.description }}
          </xzj-readMore>
        </view>
      </view>
      <view style="margin: 0 42rpx">
        <uv-line color="#b1b1b1" margin="76.744rpx 0"></uv-line>
      </view>
      <view class="online-content">
        <view v-for="(item, index) in ajaxData.lessonItems" :key="item.id" class="online-content-item" @click="onClickPaly(index)">
          <view class="image">
            <uv-image :src="item.videoCover" height="100%" width="100%" v-if="item.videoAddress"></uv-image>
            <view class="image-soon" v-else>COMING SOON</view>
          </view>
          <view class="name">
            <view class="name-text"> {{ item.lessonName }} </view>
            <view v-if="item.paymentType === 'free'" class="name-free">FREE</view>
            <view v-else-if="item.paymentType !== 'free' && !ajaxData.purchased" class="name-icon">
              <uv-icon name="jiesuo" custom-prefix="custom-icon" color="#959595" size="38.372rpx"></uv-icon>
            </view>
          </view>

          <view class="description"> {{ item.description }}</view>

          <view class="active" v-if="index === activeIndex">
            <uv-icon name="duigou" custom-prefix="custom-icon" color="#75c741" size="26.163rpx"></uv-icon>
          </view>
        </view>
      </view>
      <view style="margin: 0 42rpx">
        <uv-line color="#b1b1b1" margin="27.907rpx 0 76.744rpx 0"></uv-line>
      </view>
      <view class="attention">
        <view class="label">注意事项</view>
        <template v-if="ajaxData.attention">
          <view v-for="item in ajaxData.attention" class="item">
            <view class="dian"></view>
            <view class="text">{{ item }}</view>
          </view>
        </template>
        <template v-else> 暂无注意 </template>
      </view>
      <view class="liubai"></view>
      <view class="footer">
        <view v-if="!ajaxData.purchased" class="info">
          <view class="info-label"> 限时活动 </view>
        </view>
        <view class="price">
          <view class="existing">
            <text class="decimal">￥</text>
            <text>{{ ajaxData?.inter }}</text>
            <text>.{{ ajaxData?.decimal }}</text>
          </view>
          <view class="original"> 原价{{ ajaxData.originalPrice }} </view>
        </view>
        <view class="button" @click="onPay" :style="{ backgroundColor: ajaxData.purchased ? '#47a0f3' : '#FF7A66' }">
          <!-- 如果是ios 则提示 -->
          <!-- {{ os ? 'iOS功能不可用' : activeItems?.paymentType === 'free' ? '免费' : ajaxData.purchased ? '已解锁' : '支付' }} -->
          {{ ajaxData.purchased ? '已解锁' : '立即支付' }}
        </view>
      </view>
    </view>
    <uv-safe-bottom></uv-safe-bottom>
  </view>
  <uv-toast ref="toastRef"></uv-toast>
</template>

<script setup>
  import { ref, computed, nextTick } from 'vue';
  import { onLeft, toastFn } from '@/common/js/fn.js';
  import { onLoad, onPageScroll, onShareAppMessage } from '@dcloudio/uni-app';
  import { defaultImages, defaultImagesList, gradeOptions } from '@/common/js/global.js';
  let os = ref(uni.$uv.os() === 'ios');
  let routerVal = ref(),
    toastRef = ref();
  onLoad(option => {
    routerVal.value = Number(option.id);
    httpDetail();
  });
  const customNavHeight = computed(() => {
    return uni.$uv.sys().statusBarHeight;
  });
  // 请求接口
  let mVideoRef = ref();
  let ajaxData = ref({});
  let activeIndex = ref(0),
    activeVideo = ref(),
    activeSuccess = ref(0);
  const httpDetail = async () => {
    let data = await uni.$uv.http.post('app/online_lesson/detail', { id: routerVal.value });
    let lessonItems = data.lessonItems.map(r => {
      // 把秒转成时分
      let seconds = parseInt(r.lessonTime);
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      const formattedMinutes = String(minutes).padStart(2, '0');
      const formattedSeconds = String(remainingSeconds).padStart(2, '0');
      let obj = {
        ...r,
        lessonTime: `${formattedMinutes}:${formattedSeconds}`,
        videoCover: r.videoCover || defaultImagesList[0],
        inter: Number(r.price / 100)
          .toFixed(2)
          .toString()
          .split('.')[0],
        decimal: Number(r.price / 100)
          .toFixed(2)
          .toString()
          .split('.')[1]
      };
      return obj;
    });
    let arr = Number(data.price / 100)
      .toFixed(2)
      .toString()
      .split('.');
    let inter = arr[0],
      decimal = arr[1];
    ajaxData.value = {
      ...data,
      attention: data.attention.replace(/\n/g, '<br/>').split('<br/>'),
      lessonItems,
      inter,
      decimal,
      originalPrice: Number(data.originalPrice / 100).toString(),
      teacherDesc: data.teacherDesc || '暂无介绍'
    };
    // 如果有免费的，放免费的，没有的话，就放 内容视频
    activeIndex.value = data.lessonItems.findIndex(r => r.paymentType === 'free');
    if (activeIndex.value >= 0) {
      activeVideo.value = data.lessonItems[activeIndex.value].videoAddress;
      activeSuccess.value = activeIndex.value;
    } else {
      activeVideo.value = data.contentVideo;
      activeSuccess.value = -1;
    }
    tally('click');
  };
  const activeItems = computed(() => {
    return ajaxData.value?.lessonItems ? ajaxData.value.lessonItems[activeIndex.value] : {};
  });
  // 点击播放视频
  const onClickPaly = index => {
    if (!ajaxData.value.lessonItems[index].videoAddress) {
      toastFn(toastRef.value, '暂未上传', 'error');
      return;
    }
    activeIndex.value = index;
    // 免费 和 已购买
    if (activeItems.value.paymentType === 'free' || ajaxData.value.purchased) {
      activeVideo.value = activeItems.value.videoAddress;
      activeSuccess.value = index;
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300 // 滚动动画持续时间，单位为毫秒
      });
      return;
    }
  };
  const onPay = async () => {
    // if (os.value) {
    //   toastFn(toastRef.value, '由于相关规范，iOS功能暂不可用', 'error');
    //   return;
    // }
    if (activeItems.value.paymentType === 'free') {
      toastFn(toastRef.value, '免费课程无需购买', 'info');
      return;
    }
    if (ajaxData.value.purchased) {
      toastFn(toastRef.value, '已解锁', 'info');
      return;
    }
    // 下面是微信支付
    let data = await uni.$uv.http.post('app/online_lesson/purchase_with_cash', {
      signType: 'RSA',
      goodsID: ajaxData.value.id,
      goodsType: 'OnlineLesson'
    });
    let options = {
      provider: 'wxpay',
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: `prepay_id=${data.prepay_id}`,
      signType: 'RSA',
      paySign: `${data.paySign}`,
      _debug: 1,
      success: function (res) {
        toastFn(toastRef.value, '支付成功', 'success');
        ajaxData.value.purchased = true;
        onClickPaly(activeIndex.value);
      },
      fail: function (err) {}
    };
    uni.requestPayment(options);
  };
  let httpCollect = async () => {
    await uni.$uv.http.post(`app/collect/${!ajaxData.value.collected.id ? 'add' : 'cancel'}`, {
      classify: 'OnlineLesson', //收藏类型
      objid: ajaxData.value.id, //收藏对象的数据ID
      optype: 'collect' //操作类型
    });
    ajaxData.value.collected.id = ajaxData.value.collected.id ? 0 : 1;
    toastRef.value.show({
      overlay: false,
      message: `${ajaxData.value.collected.id ? '' : '取消'}收藏成功`,
      type: 'success'
    });
  };
  onShareAppMessage(() => {
    let pages = uni.$uv.pages();
    let url = pages[pages.length - 1]?.$page?.fullPath || '';
    let path = `${url}${url.includes('?') ? '&' : '?'}${url.includes('isShare') ? '' : 'isShare=1'}`;
    tally('share');
    return {
      title: '#去卡#按次付费，无需囤卡，#小小跳舞,快来拿捏~', // 默认为小程序名称
      imageUrl: ajaxData.value.imageUrl,
      path
    };
  });
  const tally = async val => {
    await uni.$uv.http.post(
      'app/collect/statistic',
      {
        objectableID: ajaxData.value.id,
        objectableType: 'OnlineLesson',
        operationType: val //render 展示 click 查看 share 分享 play 播放完
      },
      {
        custom: { toast: false }
      }
    );
  };
</script>

<style lang="scss" scoped>
  .online {
    background-color: #fff;
    font-family: Source Han Sans CN;
    font-size: 24.419rpx;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100vh;
    &-header {
      display: flex;
      position: relative;
      .left {
        background-color: #fff;
        height: 91rpx;
        width: 91rpx;
        background-color: rgba($color: #000000, $alpha: 0.16);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 23rpx;
        z-index: 9999;
      }
    }
    &-video {
      margin-top: -80rpx;
      &-main {
        width: 100%;
        height: 419rpx;
      }
      &-info {
        height: 76.744rpx;
        background-color: #000;
        color: #fff;
        font-size: 24.419rpx;
        display: flex;
        align-items: center;
        padding-left: 43.605rpx;
        font-weight: 900;
      }
    }
    .scroll {
      flex: 1;
      overflow-y: auto;
    }
    &-label {
      display: flex;
      height: 78rpx;
      align-items: center;
      font-size: 26.163rpx;
      .share {
        margin-left: auto;
        border-left: 1px solid #b1b1b1;
        border-right: 1px solid #b1b1b1;
        padding: 0 42rpx;
        color: #ff7a66;
      }
      .collect {
        padding: 0 42rpx;
      }
    }
    &-info {
      width: 100%;
      margin-left: -48.837rpx;
      height: 150rpx;
      padding: 22.674rpx 92.442rpx;
      box-sizing: border-box;
      background-color: #dbdbdb;
      color: #000;
      font-size: 34.884rpx;
      font-weight: 700;
    }
    &-teacher {
      margin: 17rpx 45rpx;
      margin-bottom: 0;
      color: #949494;
      .teacher {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 48.837rpx;
        .content {
          flex: 1;
          padding-left: 17rpx;
          margin-left: 17rpx;
          border-left: 1px solid #b1b1b1;
          .name {
            color: #545454;
            font-weight: bold;
            padding-bottom: 24.419rpx;
            font-size: 27.907rpx;
          }
        }
      }
      .introduce {
        padding-top: 55.814rpx;
        padding-left: 16rpx;
        .rate {
          display: flex;
          align-items: center;
          margin-bottom: 41.86rpx;
          .grade {
            width: 104.651rpx;
            height: 40.116rpx;
            line-height: 40.116rpx;
            box-sizing: border-box;
            background: rgba(97, 71, 178, 1);
            font-size: 20.93rpx;
            font-weight: 900;
            text-align: center;
            color: rgba(255, 255, 255, 1);
          }
        }
        .title {
          font-weight: bold;
          color: #545454;
          margin-bottom: 48.837rpx;
          font-size: 27.907rpx;
        }
      }
    }
    &-content {
      margin: 0 27.907rpx;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      &-item {
        width: 298.256rpx;
        margin-bottom: 48.837rpx;
        position: relative;
        .image {
          width: 100%;
          height: 162.209rpx;
          border-radius: 19.186rpx;
          overflow: hidden;
          background-color: #f0f0f0;
          display: flex;
          align-items: center;
          justify-content: center;
          &-soon {
            font-size: 24.419rpx;
            font-weight: 900;
            color: #838383;
          }
        }
        .name {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 17.442rpx;
          margin-bottom: 6.977rpx;
          color: #000;
          &-free {
            color: $dance-main-color;
            font-weight: 900;
            line-height: 20.27px;
          }
        }
        .description {
          color: #959595;
        }
        .active {
          position: absolute;
          right: 1px;
          top: 8.721rpx;
          z-index: 2;
        }
      }
    }
    .attention {
      box-shadow: 0px 1px 10px rgba(0, 0, 0, 0.1);
      margin: 0 26rpx;
      padding: 48.837rpx 33.14rpx 55.814rpx 33.14rpx;
      border-radius: 21rpx;
      color: #949494;
      font-size: 24rpx;
      .label {
        color: #545454;
        font-size: 35rpx;
        font-weight: bold;
        margin-bottom: 31rpx;
      }
      .item {
        display: flex;
        align-items: center;
        line-height: 41.86rpx;

        .dian {
          flex-shrink: 0;
          height: 17rpx;
          width: 17rpx;
          border-radius: 50%;
          background-color: #b1b1b1;
          align-self: flex-start;
        }
        .text {
          margin-left: 21rpx;
          font-size: 24rpx;
        }
      }
    }
  }
  .footer {
    height: 92rpx;
    border-radius: 21rpx;
    margin: 17rpx 26rpx;
    box-shadow: 0px 1px 10px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    overflow: hidden;
    font-size: 26rpx;
    font-weight: bold;
    line-height: 1;
    position: fixed;
    bottom: 17.442rpx;
    right: 26.163rpx;
    box-sizing: border-box;
    z-index: 999;
    .info {
      color: #ff7a66;
      background-color: #fff;
      font-size: 24.419rpx;
      font-weight: 700;
      height: 100%;
      padding: 12.209rpx 0;
      box-sizing: border-box;
      &-label {
        width: 150rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        height: 100%;
        border-right: 1px dashed #b1b1b1; /* 添加虚线边框 */
      }
    }
    .price {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      padding: 0 43.605rpx;

      .existing {
        font-size: 41.86rpx;
        font-weight: bold;
        padding-top: 17.442rpx;
        text-align: center;
        .decimal {
          font-size: 27.907rpx;
        }
      }
      .original {
        font-weight: 400;
        font-size: 24.419rpx;
        margin-bottom: 6.977rpx;
        text-align: center;
        color: #b1b1b1;
        text-decoration: line-through; /* 添加横杠 */
      }
    }
    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #47a0f3;
      font-size: 34.884rpx;
      font-weight: bold;
      color: #fff;
      height: 100%;
      padding: 17.442rpx 41.86rpx;
      box-sizing: border-box;
      width: 225rpx;
    }
  }
  .liubai {
    height: 245.93rpx;
    width: 100%;
  }
</style>
